import { _decorator, Component, log, Node,Animation, CCInteger, CCFloat, Vec3, view, Color, tween, Sprite } from 'cc';
import { GameManager } from './GameManager';
import { AudioManager } from './AudioManager';
const { ccclass, property } = _decorator;

@ccclass('duckC')
export class duckC extends Component {

    //状态100是飞翔，200是中枪，300是死亡
    zhuantai:number = 0;

    //飞翔方向 1是向左，2是向右，3是左上，4是右上
     @property(CCInteger)
    fangxiang:number = 2;

    //飞翔速度
    @property(CCInteger)
    speed:number = 150;

    //是否随机变方向
    // @property(CCInteger)
    random:number = 0;


    //角度 向上飞
    // @property(CCInteger)
    angleT:number = 140;

    //角度 左右飞
    // @property(CCInteger)
    angleLR:number = 100;

    // 缓冲区大小，可 Inspector 调整，这里是飞出去多少才死
    buffer: number = 10; 

    //保存动画组件
    private _animation: Animation | null = null;




    //是否在闪烁
    isBlinking:boolean = false;

    onLoad() {
        // 获取Animation组件
        this._animation = this.node.getComponent(Animation);

        this.schedule(() => {
            if(this.random==1){
                const array = ['flyL', 'flyR','flyTL','flyTR'];
                const randomIndex = Math.floor(Math.random() * array.length);
                this.toFly(array[randomIndex],2);
            }
        }, 2);

    }

    start() {
        // setTimeout(()=>{
        //     this.toDead();
        // }, 500);
         this.node.on(Node.EventType.TOUCH_START, this.onTouchStart, this);

        // 注册触摸结束事件（核心点击判断）
        this.node.on(Node.EventType.TOUCH_END, this.onTouchEnd, this);

        // 注册触摸取消事件（如触摸被中断）
        this.node.on(Node.EventType.TOUCH_CANCEL, this.onTouchCancel, this);
        this.startBlinkEffect();
    }

    onTouchStart(event: any) {
        log("onTouchStart");
        //正在闪烁不要中枪
        if (this.isBlinking) return;
        // 获取触摸位置
        let touchPos = event.touch.getLocation();
        // 获取节点位置
        let nodePos = this.node.getPosition();
        // 中枪
        this.toShot();
    }
    onTouchEnd(event: any) {
        log("onTouchEnd");
    }
    onTouchCancel(event: any) {
        log("onTouchCancel");
    }

    private startBlinkEffect() {
        if (this.isBlinking) return;
        // 颜色闪烁
        tween(this.getComponent(Sprite))
        .call(() => {  // 开始回调
            this.isBlinking = true;
        })
        .to(0.12, { color: new Color(255, 255,  25, 40)})
        .to(0.12, { color: new Color(255, 255, 255 ,255) })
        .union() // 组合成一个闪烁单元
        .repeat (5) 
        .call(() => {
            this.isBlinking = false;
            console.log("闪烁完成");
        })
        .start();

    }


    toFly(animationName:string,isFangx:number=0) {
        log("toFly",animationName,this.angleLR)
        
        if(isFangx==1){
            this.random=1
        }
       
        let fangxiangT=1;
        if (animationName == "flyL") {
            fangxiangT = 1;
        }
        if (animationName == "flyR") {
            fangxiangT = 2;
        }
        if (animationName == "flyTL") {
            fangxiangT = 3;
        }
        if (animationName == "flyTR") {
            fangxiangT = 4;
        }
         if (isFangx!=2) {
            AudioManager.instance.playSFX('sound/duck-quack', false);
            this.zhuantai = 100;
            let randomNum = Math.floor(Math.random() * 401) - 200;
            this.node.setPosition(randomNum, -300);
        }
       
        if (this._animation && this._animation.clips.some(clip => clip.name === animationName)) {
            this._animation.play(animationName);
            this.fangxiang = fangxiangT;
        }
    }
    toDead() {
        let animationName = "dead";
        if (this._animation && this._animation.clips.some(clip => clip.name === animationName)) {
            this._animation.play(animationName);
            this.zhuantai = 300;
        }
    }
   toShot() {
        // AudioManager.instance.playSFX('sound/on_ground1', false);
        AudioManager.instance.playSFX('sound/fall', false);
        let animationName = "shot";
        if (this._animation && this._animation.clips.some(clip => clip.name === animationName)) {
            this._animation.play(animationName);
            this.zhuantai = 200;
            setTimeout(()=>{
                this.toDead();
            }, 500);
        }
    }


    update(deltaTime: number) {
        if(this.zhuantai == 100){
            //向左飞
            if(this.fangxiang == 1){
                this.node.x -= this.speed * deltaTime;
                this.node.y += this.angleLR * deltaTime;
            }
            //向右飞
            else if(this.fangxiang == 2){
                this.node.x += this.speed * deltaTime;
                this.node.y += this.angleLR * deltaTime;
            }
            else if(this.fangxiang == 3){
                this.node.x -= this.speed * deltaTime;
                this.node.y += this.angleT * deltaTime;
            }
            else if(this.fangxiang == 4){
                this.node.x += this.speed * deltaTime;
                this.node.y += this.angleT * deltaTime;
            }
        }
         if(this.zhuantai == 300){
             this.node.y -= 200 * deltaTime;
        }


        

    
        if (this.checkOutOfScreen()) {
            log("超出范围",this.node.x,this.node.y);
            if(this.zhuantai == 300){
                GameManager.instance.duckDead(10,this.node.x);
            }else{
                GameManager.instance.duckDead(20,this.node.x);
            }
            this.destroyNode();
        }

     
    }


    //判断精灵是否飞出屏幕
   checkOutOfScreen(): boolean {
        const pos = this.node.getWorldPosition();
        const screen = view.getVisibleSize();
        return pos.x < -this.buffer || 
               pos.x > screen.width + this.buffer ||
               pos.y < -this.buffer || 
               pos.y > screen.height + this.buffer;
    }



     destroyNode() {
       
        // 销毁节点
        this.node.destroy();
        // 如果精灵节点有父节点管理，有时也需要从父节点移除
        // this.node.removeFromParent();
    }
}


